package com.atguigu.vod.service.impl;

import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.atguigu.vod.service.VodService;
import com.atguigu.vod.utils.ConstantVodUtils;
import com.atguigu.vod.utils.InitVodClient;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.List;

@Service
public class VodServiceImpl implements VodService {

    // 上传视频到阿里云视频点播
    @Override
    public String uploadVideoAly(MultipartFile file) {
        try {
            // accessKeyId, accessKeySecret
            String accessKeyId = ConstantVodUtils.ACCESS_KEY_ID;
            String accessKeySecret = ConstantVodUtils.ACCESS_KEY_SECRET;

            // fileName 上传文件的原始名称
            String fileName = file.getOriginalFilename();
            // title 上传之后显示的名称 lastIndexOf最后 一个 . 的值
            String title = fileName.substring(0, fileName.lastIndexOf("."));

            // inputStream  上传文件的输入流
            InputStream inputStream = file.getInputStream();
            UploadStreamRequest request = new UploadStreamRequest(accessKeyId, accessKeySecret, title, fileName, inputStream);

            UploadVideoImpl uploader = new UploadVideoImpl();
            UploadStreamResponse response = uploader.uploadStream(request);
            // 请求视频点播服务的请求ID
            // System.out.println("RequestId = " + response.getRequestId());
            String VideoId = "";
            if (response.isSuccess()) {
                VideoId = response.getVideoId();
                System.out.println(VideoId);
            }else {
                VideoId = response.getVideoId();
            }
            return VideoId;
        }catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }
    // 删除多个阿里云视频
    @Override
    public void removeMoreAlyVideo(List<String> videoIdList) {
        try {
            DefaultAcsClient client = InitVodClient.initVodClient(ConstantVodUtils.ACCESS_KEY_ID, ConstantVodUtils.ACCESS_KEY_SECRET);
            // 创建删除的request 对象
            DeleteVideoRequest request = new DeleteVideoRequest();
            // 设置删除的视频ids
            String videoIds = StringUtils.join(videoIdList.toArray(), ",");
            request.setVideoIds(videoIds);
            // 调用初始化方法实现删除
            client.getAcsResponse(request);
        }catch (Exception e){
            e.printStackTrace();
            throw new GuliException(20001,"删除视频失败");
        }
    }
}
